package com.stack;

/**
 * @program: letcode
 * @author: lin
 * @create: 2020-03-17 17:32
 * @description: 使用链表实现栈
 */
public class StackBasedOnLinkedList {

    private class Node{
        private int data;
        private Node next;

        public Node(int data,Node next){
            this.data = data;
            this.next = next;
        }

        public int getData(){
            return this.data;
        }

    }

    // 栈底数据
    private Node top = null;

    // 进栈
    public void push(int value){
        Node newNode = new Node(value,null);
        // 判断是否空栈
        if(top == null){
            top = newNode;
        } else {
            // 新进栈的数据保存在链表的首部
            newNode.next = top;
            top = newNode;
        }
    }

    // 出栈
    public int pop(){
        // 判断栈内是否有数据
        if(top == null){
            return -1;
        }
        int value = top.data;
        return value;
    }

    // 输出链表栈内的所有数据
    public void pringAll(){
        Node p = top;
        while (p != null){
            System.out.print(p.data+" ");
            p = p.next;
        }
        System.out.println();
    }

}
